﻿<%@ Page Language="C#" %>
<%@ Import Namespace="Backfire" %>

<script runat="server">
    
    public class Backfire4Umbraco
    {
        public static void VerifyAccessOnLoad()
        {
            HQ.SendMessageToClient(PostbackMessage.AccessGranted, HttpContext.Current.Response);
        }

        public static void ProcessChanges()
        {
            string changes = HttpContext.Current.Request.Form["backfire-changes"];
            PostbackMessage result = HQ.Process(changes, LoadCssFromFile, SaveCssToFile);
            HQ.SendMessageToClient(result, HttpContext.Current.Response);
        }

        public static string LoadCssFromFile(string uri)
        {
            uri = uri.ToLower();

            if (uri.StartsWith(GetFullyQualifiedAppPath()))
            {
                var virtualPath = uri.Substring(GetFullyQualifiedAppPath().Length);
                if (virtualPath.Contains("?"))
                    virtualPath = virtualPath.Substring(0, virtualPath.IndexOf("?"));

                string filePath = HttpContext.Current.Server.MapPath(virtualPath);

                return System.IO.File.ReadAllText(filePath);
            }

            return "";
        }

        public static bool SaveCssToFile(string uri, string contents)
        {
            uri = uri.ToLower();
            
            if(uri.StartsWith(GetFullyQualifiedAppPath()))
            {
                var virtualPath = uri.Substring(GetFullyQualifiedAppPath().Length);
                if (virtualPath.Contains("?"))
                    virtualPath = virtualPath.Substring(0, virtualPath.IndexOf("?"));

                string filePath = HttpContext.Current.Server.MapPath(virtualPath);

                System.IO.File.WriteAllText(filePath, contents);

                return true;
            }
            
            return false;
        }

        public static string GetFullyQualifiedAppPath()
        {
            var appPath = "";
            var context = HttpContext.Current;

            if (context != null)
            {
                appPath = string.Format("{0}://{1}{2}{3}",
                    context.Request.Url.Scheme,
                    context.Request.Url.Host,
                    (context.Request.Url.Port == 80) ? string.Empty : ":" + context.Request.Url.Port,
                    context.Request.ApplicationPath);
            }

            return appPath.Trim('/');
        }
    }
    
</script>

<%
    if (Request.HttpMethod == "GET")
        Backfire4Umbraco.VerifyAccessOnLoad();
    if (Request.HttpMethod == "POST")
        Backfire4Umbraco.ProcessChanges();
%>